#import "ChatView.h"
#import "SolarSeekApplication.h"
#import "Chats.h"
#import "ChatsController.h"

@implementation ChatView (ParticipantsSelected)

- (NSArray *)participantsSelected {
	NSEnumerator *e = [[nibControllerConversations arrangedObjects] objectEnumerator];
	NSMutableSet *s = [NSMutableSet set];
	Chat *chat;
	while(chat = [e nextObject]) {
		NSEnumerator *f = [[[chat peers] mutableSet] objectEnumerator];
		[s addObject:[f nextObject]];
	}
	return [s allObjects];
}

@end

@implementation ChatView




- (IBAction)say:(id)sender
{
	NSString *str = [nibTextFieldSay stringValue];
	[nibTextFieldSay setStringValue:@""];
	NSEnumerator *e = [[nibControllerConversations arrangedObjects] objectEnumerator];
	Chat *chat;
	while(chat = [e nextObject]) {
		if([chat type]==ChatTypeRoom) {
			[[[NSApp engine] chatsController] say:str toRoom:[chat room]];
		}
		else {
			[[[NSApp engine] chatsController] say:str toPeer:[chat peer]];
		}
	}
	[self updateFirstResponder];
}

- (NSTextStorage *)textStorage { return [nibTextLog textStorage]; }
- (ChatTextView *)textView { return nibTextLog; }
- (BOOL)shouldScrollToBottomAfterAppending {
	NSScrollView *scrollView = [nibTextLog enclosingScrollView];       
	NSClipView *clipView = [scrollView contentView];  
	NSRect visibleRect = [clipView documentVisibleRect],     
		totalRect = [clipView documentRect];    
	NSRect bottomRect = totalRect;    
	float y = bottomRect.size.height-1.0;   
	bottomRect.origin.y = y>=0.0?y:0.0;
	bottomRect.size.height = 1.0;   
	BOOL update = NSContainsRect(visibleRect,bottomRect);
	
	return update;
}
 

- (void)performScrollToBottom {
	[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(performScrollToBottom) object:nil];
	NSScrollView *scrollView = [nibTextLog enclosingScrollView];       
	NSClipView *clipView = [scrollView contentView];  
	NSRect visibleRect = [clipView documentVisibleRect],     
		totalRect = [clipView documentRect];    
	if(NSContainsRect(visibleRect,totalRect)==NO) {
		[nibTextLog scrollPoint:NSMakePoint(0,[nibTextLog frame].size.height-0.01)];
//		float y = [clipView documentRect].size.height;
//		[clipView scrollToPoint:NSMakePoint(0,200)];
//		[[nibTextLog enclosingScrollView] setNeedsDisplay:YES];
	}
//	NSRange r = [[self textStorage] length]==0?NSMakeRange(0,0):NSMakeRange([[self textStorage] length]-1,1);
//	[[self enclosingScrollView] setContentView:
//	[nibTextLog scrollRangeToVisible:r];
}

 - (void)scrollToBottom {
	[self performSelector:@selector(performScrollToBottom) withObject:nil afterDelay:0.01];
//	[self performScrollToBottom];
}

- (void)updateFirstResponder {
	[[nibTextFieldSay window] makeFirstResponder:nibTextFieldSay];
}
@end
